package model

import (
	"database/sql"
	"fmt"
	"github.com/jmoiron/sqlx"
	"strings"
	"time"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

type AgentInfo struct {
	Id         int64   `json:"id" db:"id"`
	Uid        int64   `json:"uid" db:"uid"`
	TypeId     int64   `json:"typeId" db:"typeId"`
	Type       int64   `json:"type" db:"type"`
	Level      int     `json:"level" db:"level"`
	Wechat     string  `json:"wechat,omitempty" db:"wechat"`
	Email      string  `json:"email,omitempty" db:"email"`
	Show       int     `json:"show" db:"show"`
	Status     int     `json:"status" db:"status"`
	ExpireTime int64   `json:"expireTime" db:"expire_time"`
	CreateTime int64   `json:"createTime" db:"create_time"`
	Discount   float64 `json:"discount" db:"discount"`
}

type AgentGoodsOrder struct {
	Id              int64   `json:"id" db:"id"`
	OrderNum        string  `json:"order_num" db:"order_num"`
	Uid             int64   `json:"uid" db:"uid"`
	Type            int     `json:"type" db:"type"`
	Level           int     `json:"level" db:"level"`
	Gid             int64   `json:"gid" db:"gid"`
	PackageId       int64   `json:"package_id" db:"package_id"`
	PayStatus       int     `json:"pay_status" db:"pay_status"`
	GoodsName       string  `json:"goods_name" db:"goods_name"`
	PackageGoodsNum int     `json:"buy_package_num,omitempty" db:"buy_package_num"`
	TotalGoodsNum   int     `json:"total_goods_num,omitempty" db:"total_goods_num"`
	PackageDiscount float64 `json:"package_discount" db:"package_discount"`
	AgentDiscount   float64 `json:"agent_discount" db:"agent_discount"`
	OriginPriceRmb  float64 `json:"origin_price_rmb" db:"origin_price_rmb"`
	OriginPrice     float64 `json:"origin_price" db:"origin_price"`
	DiscountPrice   int     `json:"discount_price" db:"discount_price"`
	TotalPrice      float64 `json:"total_price" db:"total_price"`
	Rate            float64 `json:"rate" db:"rate"`
	CreateTime      int64   `json:"create_time" db:"create_time"`
	PayTime         int64   `json:"pay_time,omitempty" db:"pay_time"`
	UpdateTime      int64   `json:"update_time,omitempty" db:"update_time"`
	Status          int     `json:"status" db:"status"`
}

// 写入日志
// Auth:hzp
type AgentInfoLog struct {
	Id          int64   `json:"id" db:"id"`
	Uid         int64   `json:"uid" db:"uid"`
	Type        int     `json:"type" db:"type"`
	BeforeLevel int     `json:"before_level" db:"before_level"`
	AfterLevel  int     `json:"after_level" db:"after_level"`
	BeforeTime  int64   `json:"before_time" db:"before_time"`
	AfterTime   int64   `json:"after_time" db:"after_time"`
	Price       float64 `json:"price" db:"price"`
	Action      int     `json:"action" db:"action"`
}

const VipCodeBuyTypeAgent = 4 //金至尊购买类型，  经销商购买
const OrderPayed = 2          //会员订单已支付常量
const OrderUnPay = 1          //会员订单未支付常量
const AgentTypeVip = 1        //会员经销商
const AgentTypeRouter = 2     //路由器经销商

const AgentActionApply = 1
const AgentActionRenew = 2
const AgentActionUpgrade = 3

//获取经销商信息
func GetAgentInfoByUid(uid int64) (info AgentInfo, err error) {
	err = sqlx.Get(config.C.DB.DB, &info, "SELECT id, uid, typeId, level, wechat, email, `show`, status, expire_time, create_time FROM agent_user WHERE uid = ? LIMIT 1", uid)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetAgentInfoByUid：", uid, err.Error())
	}
	return
}

//获取经销商类型信息
func GetAgentTypeInfoByLevel(typeId int64) (agentType AgentTypeInfo, err error) {
	err = sqlx.Get(config.C.DB.DB, &agentType, "SELECT price, discount FROM agent_type WHERE id = ? LIMIT 1", typeId)
	if err == sql.ErrNoRows {
		err = errno.RecordError
	}
	if err != nil {
		Log("err", "GetAgentTypeInfoByLevel：", typeId, err.Error())
	}
	return
}

func GetTypeIdByTypeAndLevel(agentType, level int) (res int64, err error) {
	err = sqlx.Get(config.C.DB.DB, &res, "SELECT id FROM agent_type WHERE type = ? AND level =? LIMIT 1", agentType, level)
	if err != nil {
		return 0, err
	}
	return
}

type OriginPriceInfo struct {
	Gid            int64   `json:"gid" db:"gid"`
	Period         int     `json:"period" db:"period"`
	OriginPriceRmb float64 `json:"originPriceRmb" db:"origin_price_rmb"`
	Title          string  `json:"title" db:"title"`
}

//商品原价列表
func GetGoodsOriginPrice() (price []OriginPriceInfo, err error) {
	err = sqlx.Select(config.C.DB.DB, &price, "SELECT gid, period, origin_price_rmb FROM agent_goods_info WHERE type = 1 ORDER BY period")
	if err != nil {
		Log("err", "GetGoodsOriginPrice：", err.Error())
	}
	return
}

//查询经销商兑换列表
//Auth: Xu
func GetGoodsOrderList(uid int64, date string) (orderList []AgentGoodsOrder, err error) {
	err = sqlx.Select(config.C.DB.DB, &orderList, "SELECT level,goods_name , order_num , total_price, total_goods_num, create_time FROM agent_goods_order WHERE uid = ? and pay_status = ? and FROM_UNIXTIME(create_time,'%Y-%m') = ? ORDER BY create_time desc", uid, OrderPayed, date)
	if err == sql.ErrNoRows {
		err = nil
		return
	}
	if err != nil {
		Log("err", "GetGoodsOriginPrice：", err.Error())
	}
	return
}

//根据uid查詢商品信息
//Auth: Xu
func GetGoodsInfoByGid(gid int64) (price OriginPriceInfo, err error) {
	err = sqlx.Get(config.C.DB.DB, &price, "SELECT gid, period, origin_price_rmb, title FROM agent_goods_info WHERE type = 1 and gid = ?", gid)
	if err != nil {
		Log("err", "GetGoodsInfoByGid：", err.Error())
	}
	return
}

//根据uid查詢经销商折扣信息
//Auth: Xu
func GetAgentDiscountInfoByUid(uid int64) (info AgentInfo, err error) {
	err = sqlx.Get(config.C.DB.DB, &info, "select uid, u.level, wechat, email, `show`, status, expire_time, u.create_time, discount from agent_user u LEFT JOIN agent_type t on u.typeId = t.id where uid = ?", uid)
	if err != nil {
		Log("err", "GetGoodsInfoByGid：", err.Error())
	}
	return
}

type PackageInfo struct {
	Id       int64   `json:"id" db:"id"`
	Gid      int64   `json:"gid" db:"gid"`
	Num      int     `json:"num" db:"num"`
	Discount float64 `json:"discount" db:"discount"`
}

//套餐列表
func GetPackageDiscountByGid() (discount []PackageInfo, err error) {
	err = sqlx.Select(config.C.DB.DB, &discount, "SELECT id, gid, num, discount FROM agent_goods_package ORDER BY gid, num")
	if err != nil {
		Log("err", "GetGoodsDiscount：", err.Error())
	}
	return
}

//根据商品id查询商品套餐
func GetPackageByGid(goodsId int) (discount []PackageInfo, err error) {
	err = sqlx.Select(config.C.DB.DB, &discount, "SELECT id, gid, num, discount FROM agent_goods_package where gid = ? ORDER BY discount", goodsId)
	if err != nil {
		Log("err", "GetGoodsDiscount：", err.Error())
	}
	return
}

//查询商品套餐
func GetPackageByid(packageId int) (discount PackageInfo, err error) {
	err = sqlx.Get(config.C.DB.DB, &discount, "SELECT id, gid, num, discount FROM agent_goods_package where id = ?", packageId)
	if err != nil {
		Log("err", "GetGoodsDiscount：", err.Error())
	}
	return
}

type AgentTypeInfo struct {
	Id       int64   `json:"id" db:"id"`
	Title    string  `json:"title" db:"title"`
	Level    int     `json:"level" db:"level"`
	Price    float64 `json:"price" db:"price"`
	Discount float64 `json:"discount" db:"discount"`
}

//经销商类型列表
func GetAgentDiscount() (discount []AgentTypeInfo, err error) {
	err = sqlx.Select(config.C.DB.DB, &discount, "SELECT id, title, level, price, discount FROM agent_type WHERE type = 1 ORDER BY level")
	if err != nil {
		Log("err", "GetAgentDiscount：", err.Error())
	}
	return
}

//获取套餐中某商品最大的折扣
func GetMaxDiscountByGid(gid int64) (discount float64, err error) {
	err = sqlx.Get(config.C.DB.DB, &discount, "SELECT MIN(discount) FROM agent_goods_package WHERE gid = ?", gid)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetMaxDiscountByGid：", gid, err.Error())
	}
	return
}

//更新经销商展示状态
func UpdateAgentShowStatus(uid int64, show int) (err error) {
	_, err = config.C.DB.DB.Exec("UPDATE agent_user SET `show` = ? WHERE uid = ?", show, uid)
	if err != nil {
		Log("err", "UpdateAgentShowStatus：", uid, err.Error())
	}
	return err
}

//更新经销商联系方式
func UpdateAgentContactInfo(uid int64, wechat, email string) (err error) {
	if len(wechat) == 0 && len(email) == 0 {
		return nil
	}
	sqlStr := "UPDATE agent_user SET"
	if len(wechat) > 0 {
		sqlStr += fmt.Sprintf(" wechat = '%s',", wechat)
	}
	if len(email) > 0 {
		sqlStr += fmt.Sprintf(" email = '%s',", email)
	}
	sqlStr = strings.TrimSuffix(sqlStr, ",")
	sqlStr += fmt.Sprintf(" WHERE uid = %d", uid)
	_, err = config.C.DB.DB.Exec(sqlStr)
	if err != nil {
		Log("err", "UpdateAgentContactInfo：", uid, err.Error())
	}
	return err
}

//新人榜、品质榜
type AgentRankInfo struct {
	CodeNum    int    `json:"codeNum" db:"codeNum"`
	CreateTime string `json:"createTime,omitempty" db:"create_time"`
	Name       string `json:"name" db:"nickname"`
	Uid        int64  `json:"uid" db:"uid"`
}

func GetAgentRankList(page, per int, source int) (info []AgentRankInfo, err error) {
	start := (page - 1) * per

	// 0 新人榜  1 品质榜
	if source == 0 {
		err = sqlx.Select(config.C.DB.DB, &info, "select a.uid, IFNULL(u.nickname, '') AS nickname, FROM_UNIXTIME(a.create_time, '%Y-%m-%d') AS create_time from agent_user AS a INNER JOIN user AS u ON a.uid = u.uid LEFT JOIN user_upgrade_verify AS c ON c.create_uid = a.uid WHERE a.show = 1 AND c.`status` = 1 GROUP BY a.uid ORDER BY a.create_time DESC, uid DESC LIMIT ?, ?", start, per)
	} else {
		err = sqlx.Select(config.C.DB.DB, &info, "select a.uid, IFNULL(u.nickname, '') AS nickname, count(*) AS codeNum from agent_user AS a INNER JOIN user AS u ON a.uid = u.uid LEFT JOIN user_upgrade_verify AS c ON a.uid = c.create_uid Where c.status = 1 AND c.source = 4 AND a.show = 1 GROUP BY c.create_uid ORDER BY codeNum DESC, uid DESC LIMIT ?, ?", start, per)
	}
	if err != nil {
		Log("err", "GetAgentRankList：", "source：", source, err.Error())
	}
	return info, err
}

type TopAgentInfo struct {
	CodeNum int    `json:"-" db:"codeNum"`
	Name    string `json:"name" db:"nickname"`
	Uid     int64  `json:"uid" db:"uid"`
	Pic     string `json:"pic" db:"userpic"`
	Wechat  string `json:"wechat,omitempty" db:"wechat"`
	Email   string `json:"email,omitempty" db:"email"`
}

//品质榜前三
func GetTopAgentInfoList() (info []TopAgentInfo, err error) {
	err = sqlx.Select(config.C.DB.DB, &info, "select c.create_uid AS uid, IFNULL(u.nickname, '') AS nickname, CONCAT('"+config.C.Domains.Ftp+"', u.userpic) as userpic, count(*) AS codeNum, a.wechat, a.email from user_upgrade_verify AS c INNER JOIN user AS u ON c.create_uid = u.uid LEFT JOIN agent_user AS a ON a.uid = u.uid Where c.status = 1 AND c.source = 4 AND a.show = 1 GROUP BY c.create_uid ORDER BY codeNum DESC LIMIT 3")
	if err != nil {
		Log("err", "GetTopAgentInfoList：", err.Error())
	}
	return info, err
}

type UpgradeCodeTotalNum struct {
	SoldNum   int `json:"soldNum" db:"soldNum"`
	UnsoldNum int `json:"unsoldNum" db:"unsoldNum"`
}

//用户升级码总数
func GetUpgradeCodeTotalNum(uid int64) (info UpgradeCodeTotalNum, err error) {
	err = sqlx.Get(config.C.DB.DB, &info, "SELECT * FROM ((SELECT count(*) AS unsoldNum FROM user_upgrade_verify WHERE saled=0 AND source = 4 AND create_uid=?) AS a),((SELECT count(*) AS soldNum FROM user_upgrade_verify WHERE saled=1 AND source = 4 AND create_uid=?) AS b)", uid, uid)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetUpgradeCodeTotalNum：", uid, err.Error())
	}
	return
}

type UpgradeCodeNum struct {
	OneMonthNum       int `json:"oneMonthNum" db:"oneMonthNum"`
	OneMonthUnusedNum int `json:"oneMonthUnusedNum" db:"oneMonthUnusedNum"`
	SixMonthNum       int `json:"sixMonthNum" db:"sixMonthNum"`
	SixMonthUnusedNum int `json:"sixMonthUnusedNum" db:"sixMonthUnusedNum"`
	OneYearNum        int `json:"oneYearNum" db:"oneYearNum"`
	OneYearUnusedNum  int `json:"oneYearUnusedNum" db:"oneYearUnusedNum"`
	ExpiredNum        int `json:"expiredNum" db:"expiredNum"`
}

//升级码类型总数
//  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1-正常状态 2-已使用 3-已作废',
//  `saled` tinyint(4) NOT NULL DEFAULT '0' COMMENT '售出状态：0-未售出，1-已售出',
func GetUpgradeCodeNum(uid int64, saled int) (info UpgradeCodeNum, err error) {
	err = sqlx.Get(config.C.DB.DB, &info, "SELECT * FROM"+
		" ((SELECT count(*) AS oneMonthNum FROM user_upgrade_verify WHERE create_uid = ? AND `status` != 3 AND saled = ? AND period = 30 AND source = 4) AS a),"+
		" ((SELECT count(*) AS oneMonthUnusedNum FROM user_upgrade_verify WHERE create_uid = ? AND `status` = 1 AND saled = ? AND period = 30 AND source = 4) AS b),"+
		" ((SELECT count(*) AS sixMonthNum FROM user_upgrade_verify WHERE create_uid = ? AND `status` != 3 AND saled = ? AND period = 30*6 AND source = 4) AS c),"+
		" ((SELECT count(*) AS sixMonthUnusedNum FROM user_upgrade_verify WHERE create_uid = ? AND `status` = 1 AND saled = ? AND period = 30*6 AND source = 4) AS d),"+
		" ((SELECT count(*) AS oneYearNum FROM user_upgrade_verify WHERE create_uid = ? AND `status` != 3 AND saled = ? AND period = 30*12 AND source = 4) AS e),"+
		" ((SELECT count(*) AS oneYearUnusedNum FROM user_upgrade_verify WHERE create_uid = ? AND `status` = 1 AND saled = ? AND period = 30*12 AND source = 4) AS f),"+
		" ((SELECT count(*) AS expiredNum FROM user_upgrade_verify WHERE create_uid = ? AND `status` = 3 AND saled = ? AND source = 4) AS g)", uid, saled, uid, saled, uid, saled, uid, saled, uid, saled, uid, saled, uid, saled)
	if err == sql.ErrNoRows {
		err = nil
	}
	if err != nil {
		Log("err", "GetUpgradeCodeNum：", uid, err.Error())
	}
	return
}

type UpgradeInfo struct {
	Id         int64  `json:"id" db:"id"`
	Code       string `json:"code" db:"code"`
	Status     int    `json:"status" db:"status"`
	CreateTime string `json:"createTime" db:"createTime"`
}

//获取升级码列表（peroid 0-已过期，已天为单位，sale 0-未售出  1-已售出）
func GetUpgradeCodeList(uid int64, peroid, sale int, page, per int) (info []UpgradeInfo, err error) {
	start := (page - 1) * per

	if peroid <= 0 {
		err = sqlx.Select(config.C.DB.DB, &info, "select id, `code`, FROM_UNIXTIME(create_time,'%Y-%m-%d') AS createTime, period as `status` FROM user_upgrade_verify WHERE create_uid = ? AND source = 4 AND saled = ? AND `status` = 3 ORDER BY id DESC LIMIT ?, ?", uid, sale, start, per)
	} else {
		err = sqlx.Select(config.C.DB.DB, &info, "select id, `code`, FROM_UNIXTIME(create_time,'%Y-%m-%d') AS createTime, `status` FROM user_upgrade_verify WHERE create_uid = ? AND source = 4 AND saled = ? AND `status` != 3 AND period = ? ORDER BY id DESC LIMIT ?, ?", uid, sale, peroid, start, per)
	}
	if err != nil {
		Log("err", "GetUpgradeList：", err.Error())
	}
	return
}

//更新升级码售卖状态
func UpdateUpgradeCodeSaleStatus(uid int64, sale int, ids string) (row int64, err error) {
	sqlStr := fmt.Sprintf("UPDATE user_upgrade_verify SET saled = %d WHERE create_uid = %d and id IN(%s)", sale, uid, ids)
	res, err := config.C.DB.DB.Exec(sqlStr)
	if err != nil {
		Log("err", "UpdateUpgradeCodeSaleStatus：", uid, err.Error())
		return 0, err
	}
	r, err := res.RowsAffected()
	if err != nil {
		Log("err", "UpdateUpgradeCodeSaleStatus：RowsAffected:", uid, err.Error())
		return 0, err
	}
	if r <= 0 {
		return 0, errno.RecordError
	}
	return r, nil
}

func AddAgentUserLog(info AgentInfoLog) (err error) {
	res := sqlx.MustExec(config.C.DB.DB, "INSERT INTO agent_user_log (uid,type,before_level,after_level,before_time,after_time,price,"+
		"action,create_time) VALUES (?,?,?,?,?,?,?,?,UNIX_TIMESTAMP(NOW()))", info.Uid, info.Type, info.BeforeLevel, info.AfterLevel,
		info.BeforeTime, info.AfterTime, info.Price, info.Action)
	r, err := res.LastInsertId()
	if err != nil {
		return err
	}
	if r <= 0 {
		return errno.RecordError
	}
	return nil
}

// 生成兑换金至尊订单
//Auth: Xu
func InsertGoodsOrder(db sqlx.Execer, data AgentGoodsOrder) (err error) {
	var rowId int64
	r, err := db.Exec("INSERT INTO agent_goods_order (order_num, uid, `level`, gid, package_id, pay_status, total_goods_num, agent_discount, package_discount, origin_price_rmb, total_price, rate, create_time, goods_name) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", data.OrderNum, data.Uid, data.Level, data.Gid, data.PackageId, data.PayStatus, data.TotalGoodsNum, data.AgentDiscount, data.PackageDiscount, data.OriginPriceRmb, data.TotalPrice, data.Rate, data.CreateTime, data.GoodsName)
	if err == nil {
		rowId, err = r.RowsAffected()
	} else {
		Log("err", err.Error())
		rowId = 0
	}

	if rowId <= 0 {
		return errno.DbError
	}
	return
}

//根据订单号查询订单信息
//Auth:Xu
func GetGoodsOrderInfoByNo(db sqlx.Queryer, orderNo string) (orderInfo AgentGoodsOrder, err error) {
	orderNo = strings.Replace(orderNo, " ", "", -1)
	err = sqlx.Get(config.C.DB.DB, &orderInfo, "SELECT order_num, uid, `level`, gid, package_id, pay_status, total_goods_num, agent_discount, package_discount, origin_price_rmb, total_price, rate, create_time"+
		" FROM agent_goods_order WHERE order_num = ?", orderNo)
	if err != nil {
		Log("err", err.Error())
		return
	}
	return
}

//插入金至尊兑换码
//Auth:Xu
func InsertUpgrade(db sqlx.Execer, uid int64, code string, period int, orderNo string) (err error) {
	var rowId int64
	r, err := db.Exec("INSERT INTO user_upgrade_verify (code, create_uid, `create_time`, period, source,order_num) values(?,?,?,?,?,?)", code, uid, time.Now().Unix(), period, VipCodeBuyTypeAgent, orderNo)
	if err == nil {
		rowId, err = r.RowsAffected()
	} else {
		Log("err", err.Error())
		rowId = 0
	}

	if rowId <= 0 {
		return errno.DbError
	}
	return
}

//兑换码已全部生成，则修改updateTime
//Auth:Xu
func UpdateGoodsOrder(db sqlx.Execer, orderNo string) (err error) {
	var rowId int64
	r, err := db.Exec("UPDATE agent_goods_order set  update_time = ? where order_num = ? ", time.Now().Unix(), orderNo)
	if err == nil {
		rowId, err = r.RowsAffected()
	} else {
		Log("err", err.Error())
		rowId = 0
	}

	if rowId <= 0 {
		return errno.DbError
	}
	return
}

//修改兑换金至尊订单的支付状态
func UpdateGoodsOrderPayStatus(db sqlx.Execer, timeNowInt64 int64, orderNo string) (err error) {
	_, err = db.Exec("UPDATE `agent_goods_order` SET `pay_status` = ?, pay_time = ? WHERE `order_num` = ?",
		OrderPayed, timeNowInt64, orderNo)
	if err != nil {
		Log("err", orderNo, err.Error())
	}
	return
}

//根据订单号查询兑换成功的金至尊数量
//Auth:Xu
func GetCodeNumSuccByOrderNo(db sqlx.Queryer, orderNo string) (codeNum int, err error) {
	orderNo = strings.Replace(orderNo, " ", "", -1)
	err = sqlx.Get(config.C.DB.DB, &codeNum, "SELECT count(*) FROM user_upgrade_verify WHERE order_num = ?", orderNo)
	if err != nil {
		Log("err", err.Error())
		return
	}
	return
}

// 更新过期的经销商为已过期
func UpdateExpiredAgent(db sqlx.Execer) (err error) {

	var rowId, count int64
	err = sqlx.Get(config.C.DB.DB, &count, "SELECT count(*) FROM agent_user WHERE expire_time <=  UNIX_TIMESTAMP(NOW()) and status <> 2")
	if err != nil {
		return err
	}

	if count <= 0 {
		return nil
	}

	r, err := db.Exec("UPDATE agent_user set update_time = UNIX_TIMESTAMP(NOW()), `status` = 2, `show` = 0 where expire_time <=  UNIX_TIMESTAMP(NOW())")
	if err == nil {
		rowId, err = r.RowsAffected()
	} else {
		Log("err", err.Error())
		rowId = 0
	}

	if rowId <= 0 {
		return errno.DbError
	}
	return
}

//插入经销商信息
//Auth:Xu
func InsertAgentUserInfo(db sqlx.Execer, agentInfo AgentInfo) (id int64, err error) {
	res, err := db.Exec("INSERT INTO agent_user (uid,`typeId`,`type`,`level`,wechat,email,`show`,`status`,expire_time,"+
		"create_time,update_time) VALUES (?,?,?,?,'','',0,1,UNIX_TIMESTAMP(DATE_ADD(CURDATE(), INTERVAL 1 YEAR)),"+
		"UNIX_TIMESTAMP(NOW()),0);", agentInfo.Uid, agentInfo.TypeId, agentInfo.Type, agentInfo.Level)
	if err != nil {
		Log("err", err.Error())
	}
	id, _ = res.LastInsertId()

	return
}

//修改会员经销商等级
//Auth:Xu
func UpdateAgentGrade(db sqlx.Execer, typeId, agentType int64, level int, expireTime, agentId int64) error {
	_, err := db.Exec("UPDATE agent_user SET typeId = ?, `type`=?, `level` = ?, `status` = 1, expire_time = ?, "+
		" update_time = UNIX_TIMESTAMP(NOW()) WHERE id = ? ",
		typeId, agentType, level, expireTime, agentId)
	if err != nil {
		Log("err", err.Error())
	}
	return err
}

//插入会员经销商申请记录
//Auth:Xu
func InsertAgentUserLog(db sqlx.Execer, logData AgentInfoLog) (logId int64, err error) {
	res, err := db.Exec("INSERT INTO agent_user_log (uid,type,before_level,after_level,before_time,after_time,price,action,create_time) VALUES (?,?,?,?,?,?,?,?,UNIX_TIMESTAMP(NOW()))",
		logData.Uid, logData.Type, logData.BeforeLevel, logData.AfterLevel, logData.BeforeTime, logData.AfterTime, logData.Price, logData.Action)
	if err != nil {
		Log("err", err.Error())
	}
	logId, err = res.LastInsertId()

	return
}
